// 订单
const {auth} = require("../utils");
const router = require('koa-router')()
const Order = require('../models/orders')
const Goods = require("../models/goods");
const Users = require('../models/users')

// 查询订单
router.get('/',auth, async function (ctx, next) {
    ctx.body = await Order.find({user: ctx.state.user._id}).populate(['goods','user','shop','deliver']).sort({'createdAt':-1})
})

const  orderPrice = (goods)=> {
    return new Promise( (res, err) => {
        let price = 0
        for (let goodsKey in goods) {
            console.log(goodsKey)
            Goods.findById(goods[goodsKey]).then(res => {
                price += res.price
            })
        }
        setTimeout(()=>{
            res(price)
        },300)

    });
}

// 创建订单
router.post('/',auth,async function (ctx, next) {
    ctx.verifyParams({
        goods: {type: "array", required: true},
        shop: {type: "string", required: true},
        address:{type:"object",required:true}
    })
    ctx.request.body.price = await orderPrice(ctx.request.body.goods)
    ctx.request.body.user =  ctx.state.user._id
    ctx.request.body.code = Math.floor(Math.random()*(9999-1000))+1000  //订单编号
    ctx.body = await Order.create(ctx.request.body)

})

// 修改订单信
router.put('/plan/:id/:plan',auth, async function (ctx, next) {
    await Order.findByIdAndUpdate(ctx.params.id,{plan:ctx.params.plan})
    ctx.body = await Order.findById(ctx.params.id).populate(['goods','user','shop'])
})

// 骑手可接单
router.get('/deliver', async function(ctx,next){
    ctx.body = await Order.find({plan:1}).populate(['goods','user','shop'])
})

// 骑手接单
router.post('/deliver/:id', auth,async function(ctx,next){
    let order = await Order.findById(ctx.params.id)
    if(order.plan == 1){
        await Order.findByIdAndUpdate(ctx.params.id,{deliver:ctx.state.user._id, plan:2})
        ctx.body = await Order.findById(ctx.params.id).populate(['goods','user','shop'])
    }else {
        ctx.throw(404, '订单被抢走了');
    }
})

// 骑手送达
router.post('/deliverOrder/:id', auth,async function(ctx,next){
    let order = await Order.findById(ctx.params.id)
    if(order.plan == 3){
        await Order.findByIdAndUpdate(ctx.params.id,{deliver:ctx.state.user._id, plan:4})
        ctx.body = await Order.findById(ctx.params.id).populate(['goods','user','shop','deliver'])
    }else {
        ctx.throw(404, '店铺还未出货');
    }

})

//骑手配送记录
router.get('/deliverLi', auth, async function (ctx, next) {
    ctx.body = await Order.find({deliver:ctx.state.user._id}).populate(['goods','user','shop','deliver']).sort({'createdAt':-1})
})

// 店铺接单
router.get('/shop', auth, async function(ctx,next){
    let user = await Users.findById(ctx.state.user._id)
    ctx.body =await Order.find({shop:user.shop,plan:2}).populate(['goods','user','shop','deliver'])
})

// 店铺出货
router.post('/shop/:id', async function(ctx,next){
    let order = await Order.findById(ctx.params.id)
    if(order.plan != 2){
        ctx.throw(409, '订单状态错误');
    }
    await Order.findByIdAndUpdate(ctx.params.id,{ plan:3})
    ctx.status = 206
})

// 店铺销售记录
router.get('/li', auth,async function(ctx,next){
    let user = await Users.findById(ctx.state.user._id)
    ctx.body = await Order.find({shop:user.shop}).populate(['goods','user','shop']).sort({'createdAt':-1})
})

// 删除订单
router.delete('/:id',auth,async function(ctx){
    let order = await Order.findByIdAndDelete(ctx.params.id)
    if(!order){
        ctx.throw(404, '店铺不存在');
    }
    ctx.status = 204;
})

module.exports = router